package com.felix.thread.producer.consumer;

import java.util.Random;
import java.util.Vector;

/**
 * ProducerConsumerWaitNotifyDemo
 *
 * @author xuejinhua
 * @date 2018/10/25 16:35
 */
public class ProducerConsumerWaitNotifyDemo {
}

class Consumer implements Runnable {

    private String name;
    /**
     * 公共资源
     */
    private final Vector sharedQueue;

    public Consumer(Vector sharedQueue, String name) {
        this.sharedQueue = sharedQueue;
        this.name = name;
    }

    @Override
    public void run() {

        Random r = new Random();

        System.out.println("start consumer name = " + name);
        try {
            while (true) {
                // 模拟延迟
                Thread.sleep(r.nextInt(1000));
                // 当队列空时阻塞等待
                while (sharedQueue.isEmpty()) {
                    synchronized (sharedQueue) {
                        System.out.println("Queue is empty, consumer " + name + " is waiting, size: " + sharedQueue.size());
                        sharedQueue.wait();
                    }
                }
                // 队列不空时持续消费元素
                synchronized (sharedQueue) {
                    System.out.println("consumer name is " + name + " consumer consume data: " + sharedQueue.remove(0) + ", size: " +
                            sharedQueue.size());
                    sharedQueue.notifyAll();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
